package com.yyq.adms.usermanage.bpo.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yyq.adms.sysmanage.pojo.SysModules;
import com.yyq.adms.usermanage.bpo.SysUsersBpo;
import com.yyq.adms.usermanage.dao.SysUsersDao;
import com.yyq.adms.usermanage.pojo.SysDepts;
import com.yyq.adms.usermanage.pojo.SysPerm;
import com.yyq.adms.usermanage.pojo.SysRPM;
import com.yyq.adms.usermanage.pojo.SysRoles;
import com.yyq.adms.usermanage.pojo.SysUsers;
import com.yyq.adms.usermanage.pojo.SysUsersRoles;
import com.yyq.sos.permission.LoginUser;
import com.yyq.sos.pojo.PermissionVO;
import com.yyq.sos.service.BaseBpoImpl;
@Transactional
@Service("sysUsersBpo")
public class SysUsersBpoImpl extends BaseBpoImpl implements SysUsersBpo {

	private SysUsersDao dao;

	@Resource(name="sysUsersDao")
	public void setDao(SysUsersDao dao) {
		this.dao = dao;
		this.setBaseDao(dao);
	}

	public boolean update(Object obj){
		SysUsers user = (SysUsers) obj;
		if(user.getPassword()!=null)
		{
			//user.setPassword(EncryptUtil.encrypt(user.getPassword()));
			user.setPassword(user.getPassword());
			user.setPwd_modified_time(new Date());//设置密码修改时间
		}
		return super.update(user);
	}

	public Object findByPk(Serializable id)
	{
		SysUsers user = (SysUsers) super.findByPk(id);
		//user.setPassword(EncryptUtil.decode(user.getPassword()));
		return user;
	}

	/**
	 * 用户登录时在数据库中查找该用户
	 */
	public SysUsers login(SysUsers vo) {
		SysUsers obj = (SysUsers) dao.findByPk("from "
				+ SysUsers.class.getName() + " where userName='"
				+ vo.getUserName() + "'");
		if (obj == null)//账号是否存在
			return null;
		else
			return obj;
	}

	/**
	 * 取得用户角色
	 */
	public List getUserRoles(SysUsers vo) {
		List roles = this.search("from "+SysRoles.class.getName());//sysRolesBpo.list();
		List userRoles = this.search("from " + SysUsersRoles.class.getName() + " where userId=" + vo.getId());
		for (int i = 0, count = roles.size(); i < count; i++) {
			SysRoles role = (SysRoles) roles.get(i);
			for(int j=0, length = userRoles.size(); j < length; ++j){
				SysUsersRoles sur = (SysUsersRoles) userRoles.get(j);
				if(role.getId().intValue()==sur.getRoleId().intValue()){
					role.setCheck(true);
					if(sur.getIsGrant().equals("1"))
						role.setGrant(true);
					break;
				}
			}
		}
		return roles;
	}

	/**
	 * 更新用户角色
	 */
	public boolean updateUserRoles(SysUsers vo, String[] roleIds,String[] grantIds) {
		String delete_sql = "delete " + SysUsersRoles.class.getName() + " where userId=" + vo.getId();
		if(!dao.execHql(delete_sql))
			return false;
		List grants = new ArrayList();
		if(grantIds != null)
			for(int i=0, count = grantIds.length; i < count; ++i)
				grants.add(grantIds[i]);
		List urs = new ArrayList();
		LoginUser user = (LoginUser)LoginUser.userThread.get();
		if(roleIds!=null) {
			for (int i = 0, count = roleIds.length; i < count; i++) {
				SysUsersRoles obj = new SysUsersRoles();
				obj.setUserId(vo.getId());
				obj.setRoleId(new Long(Long.parseLong(roleIds[i])));
				obj.setGrantor(user.getUserId());
				if(grants.contains(roleIds[i]))
					obj.setIsGrant("1");
				urs.add(obj);
			}
			if(this.save(urs.toArray(new SysUsersRoles[0]))==null)
				return false;
		}
		return true;
	}

	public List getModulePermByUser(LoginUser user) {
		String sql = "select distinct m.moduleId, p.permName from "
				+ SysUsers.class.getName()
				+ " u,"
				+ SysUsersRoles.class.getName()
				+ " ur,"
				+ SysRoles.class.getName()
				+ " r,"
				+ SysRPM.class.getName()
				+ " rpm,"
				+ SysModules.class.getName()
				+ " m,"
				+ SysPerm.class.getName()
				+ " p"
				+ " where u.userId="
				+ user.getUserId().longValue()
				+ " and u.userId=ur.userId and u.sts='ACTV'"
				+ " and ur.roleId=r.roleId and r.sts='ACTV'"
				+ " and ur.roleId=rpm.roleId and rpm.permId=p.permId"
				+ " and rpm.moduleId=m.moduleId and m.parentId!=0";
		return super.search(sql);
	}

	public Map<String,List<String>> getPermission(long userId) {
		String sql = "select DISTINCT m.module_name,p.perm_name " +
				"from ss_sys_modules m join ss_sys_role_perm_module rpm " +
				"on m.id=rpm.module_id join ss_sys_perm p on p.id=rpm.perm_id " +
				"join ss_sys_users_roles ur on rpm.role_id=ur.role_id " +
				"where ur.user_id="+userId+" order by m.module_name";
		List list = dao.listSql(sql);
		Map<String,List<String>> map = new HashMap<String,List<String>>();
		for(int i=0;i<list.size();i++){
			Object[] obj = (Object[])list.get(i);
			List<String> data =  map.get(obj[0].toString());
			if(data == null){
				data = new ArrayList<String>();
				map.put(obj[0].toString(), data);
			}
			data.add(obj[1].toString());
			
		}
		return map;
	}

	public SysDepts getOrgDept(SysDepts pd) {
		if(pd.getParentId().intValue()==0){
			return pd;
		}else{
			List list = dao.search("from " + SysDepts.class.getName()
					+ " o where o.id=" + pd.getParentId());
			pd = (SysDepts) list.get(0);
			if(pd.getParentId().intValue() != 0){
				getOrgDept(pd);
			}else{
				return pd;
			}
		}
		return null;
	}

	public void doOperationMap(LoginUser user) {
		String sql = null;
		if(user.getUserId().intValue() != 1){
			sql  = "select m.id,p.perm_name from ss_sys_users u join ss_sys_users_roles ur on u.id=ur.user_id join ss_sys_roles "+
					"r on ur.role_id=r.id join ss_sys_role_perm_module rpm on r.id=rpm.role_id "+ 
					"join ss_sys_modules m on rpm.module_id=m.id join ss_sys_perm p on rpm.perm_id=p.id "+
					"where u.id="+user.getUserId()+" and u.sts='ACTV' and r.sts='ACTV' and m.parent_id!=0";
			List result = dao.listSql(sql);
			Map map = new HashMap();
			for(Object obj : result){
				Object[] objs = (Object[])obj;
				int moduleId = new Integer(objs[0].toString());
				List list = (List) map.get(moduleId);
				if(list == null){
					list = new ArrayList();
					map.put(moduleId, list);
				}
				list.add(objs[1]);
			}
			user.setOperationMap(map);
		}
		
	}

	
}
